package utils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import support.LogUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;

public class WeiXinUtils {

    private static String APP_ID = "wxfa609938e2a2880e";

    private static String APP_SECRET = "d3fc008c731c166310ae898714e4d633";

    public static WxMaService WX_MA_SERVICE = null;

    public static WxMaService wxMaService() {
        if (WX_MA_SERVICE == null) {
            //实例这个 WxMaConfig
            WxMaConfig wxMaConfig = new WxMaDefaultConfigImpl();
            ((WxMaDefaultConfigImpl) wxMaConfig).setAppid(StringUtils.trimToNull(APP_ID));
            ((WxMaDefaultConfigImpl) wxMaConfig).setSecret(StringUtils.trimToNull(APP_SECRET));
            WxMaService wxMaService = new WxMaServiceImpl();
            //设置配置文件
            wxMaService.setWxMaConfig(wxMaConfig);
            WX_MA_SERVICE = wxMaService;
        }
        return WX_MA_SERVICE;
    }


    public static JSONObject getConnect(String code) {
        String url =
                "https://api.weixin.qq.com/sns/jscode2session?" + "appid=" + APP_ID + "&" + "secret=" + APP_SECRET + "&" + "js_code" +
                        "=" + code + "&" + "grant_type=authorization_code";
        String result = HttpUtil.createGet(url).execute().body();
        return JSONUtil.parseObj(result);
    }

    /**
     * 解密，获取微信信息
     *
     * @param encryptedData 加密信息
     * @param sessionKey    微信sessionKey
     * @param iv            微信揭秘参数
     * @return 用户信息
     */
    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
        LogUtils.ERROR_LOGGER.info("encryptedData:{},sessionKey:{},iv:{}", encryptedData, sessionKey, iv);
        //被加密的数据
        byte[] dataByte = Base64.getDecoder().decode(encryptedData);
        //加密秘钥
        byte[] keyByte = Base64.getDecoder().decode(sessionKey);
        //偏移量
        byte[] ivByte = Base64.getDecoder().decode(iv);
        try {
            //如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            //初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            //初始化
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONUtil.parseObj(result);
            }
        } catch (Exception e) {
            LogUtils.ERROR_LOGGER.error("解密，获取微信信息错误", e);
        }
        throw new RuntimeException("登陆失败");
    }
}
